// src/datastore/index.js
// 主进程使用Node适配器
import { JSONFile } from 'lowdb/node';

// 渲染进程使用浏览器适配器
import { LocalStorage } from 'lowdb/browser';

import LodashId from 'lodash-id'
import path from 'node:path'
import { app } from 'electron'

// 初始化数据库
const adapter = process.env.IS_ELECTRON
  ? new JSONFile('db.json')
  : new LocalStorage('db')
const db = new Low(adapter)

// 扩展lodash-id功能
db.chain = db.chain.extend(LodashId)

// 初始化默认数据
db.read().then(() => {
  db.data ||= {
    version: 1,
    user: [],
    category: [],
    assets: [],
    incomeAndExpenditure: []
  }

  // 初始化用户
  if (db.data.user.length === 0) {
    db.data.user.push({
      id: db.chain.__id(),
      userId: 'admin',
      password: '123456'
    })
  }

  // 初始化分类
  const defaultCategories = [
    { id: db.chain.__id(), category: "breakfast", remark: "daily breakfast expenses" },
    { id: db.chain.__id(), category: "dinner", remark: "daily dinner expenses" },
    { id: db.chain.__id(), category: "lunch", remark: "Daily lunch expenses" }
  ]
  
  if (db.data.category.length === 0) {
    db.data.category.push(...defaultCategories)
  }

  // 初始化资产
  const defaultAssets = [
    { id: db.chain.__id(), assetsName: 'me', assetsDetailed: 'My assets', assetsAmountOfMoney: 0 },
    { id: db.chain.__id(), assetsName: 'wife', assetsDetailed: "My wife's assets", assetsAmountOfMoney: 0 }
  ]
  
  if (db.data.assets.length === 0) {
    db.data.assets.push(...defaultAssets)
  }

  return db.write()
})

export default db